#ifndef __UDP_CLIENT_HPP__
#define __UDP_CLIENT_HPP__

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>

// 编写测试UDP服务器
class UdpClient
{
private:
    // 一个套接字对象即可
    int _sock;
public:
    UdpClient()
    {
        // 初始化
        _sock = socket(AF_INET, SOCK_DGRAM, 0);  // IPV4协议族，数据报式传输，0自动识别类型
        if (_sock < 0){
            std::cout << "socket error" << std::endl;
            exit(0);
        }

        // client不需要绑定port，会在第一次发送时自动匹配
    }

    void start(uint16_t serverPort, const std::string& serverIp)
    {
        struct sockaddr_in server;
        bzero(&server, sizeof server);
        server.sin_family = AF_INET;
        server.sin_port = htons(serverPort);
        server.sin_addr.s_addr = inet_addr(serverIp.c_str());
        socklen_t client_size = sizeof server;

        char buffer[1024];
        std::string temp;
        while (true)
        {
            std::cout << "请输入你对猫猫想干什么# ";
            std::getline(std::cin, temp);
            ssize_t num = sendto(_sock, temp.c_str(), temp.size(), 0, (sockaddr*)&server, client_size);
            std::cout << "成功发送" << num << "\n";

            ssize_t n = recvfrom(_sock, buffer, 1024, 0, (sockaddr*)&server, &client_size);
            if (n > 0)
            {
                buffer[n] = '\0';
                std::cout << "猫猫# "<< buffer << "\n";
            }
        }
    }


    ~UdpClient()
    {
        if (_sock > 0) close(_sock);
    }
};

#endif